﻿using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.Extensions.Logging;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System;
using System.IO;
using System.Resources;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;
using static Lhxzn.LangExtractor.IniFile;
using static System.Collections.Specialized.BitVector32;
using System.Text;
using System.Text.RegularExpressions;
using static Lhxzn.LangExtractor.AnnotationManager;
using System.Runtime.InteropServices;

namespace Lhxzn.LangExtractor
{
    public partial class MainForm : Form
    {
        #region 成员变量

        #region private

        #endregion


        #region protected
        #endregion


        #region public
        /// <summary>
        /// 语言文件管理
        /// </summary>
        public LngFileManager LngFileManager { get; set; } = new LngFileManager();

        #endregion

        #endregion


        #region 构造函数
        public MainForm()
        {
            InitializeComponent();
            SetEvents();
        }

        #endregion

        #region 父类函数重载、接口实现
        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this.WindowState = FormWindowState.Maximized;
            Uc_TextEditor.LngFileManager = LngFileManager;
        }

        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            base.OnFormClosed(e);
        }

        /// <summary>
        /// 退出前询问
        /// </summary>
        /// <param name="e"></param>
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (LngFileManager.CurrentPackage != null)
            {
                DialogResult result = MessageBox.Show("是否保存并退出？", "退出", MessageBoxButtons.YesNoCancel);
                if (result == DialogResult.Yes)
                {
                    LngFileManager.CurrentPackage.Write();
                }
                else if (result == DialogResult.Cancel)
                {
                    e.Cancel = true;
                }
            }
            base.OnFormClosing(e);
        }

        /// <summary>
        /// 快捷键
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="keyData"></param>
        /// <returns></returns>
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == (Keys.Control | Keys.D1))
            {
                OnClickLastAnnotion(null, null);
                return true;
            }
            if (keyData == (Keys.Control | Keys.D2))
            {
                OnClickNextAnnotation(null, null);
                return true;
            }
            if (keyData == (Keys.Control | Keys.D3))
            {
                OnClickAnnotateRows(null, null);
                return true;
            }
            if (keyData == (Keys.Control | Keys.D4))
            {
                OnClickUnAnotateRows(null, null);
                return true;
            }
            if (keyData == (Keys.Control | Keys.F))
            {
                OnClickSearch(null, null);
                return true;
            }
            if (keyData == (Keys.Control | Keys.S))
            {
                OnClickSave(null, null);
                return true;
            }

            return base.ProcessCmdKey(ref msg, keyData);
        }

        #endregion

        #region 函数

        #region private
        /// <summary>
        /// 项目读取状态栏刷新函数，用于委托给异步打开项目的函数
        /// </summary>
        /// <param name="progress"></param>
        private void PojectLoadUpdateStatusBar(ProjectLoadProgress progress)
        {
            Invoke(new Action(() =>
            {
                tssl_status.Text =
                $"打开项目[{progress.FilePath}]" +
                $"|用时{progress.ElapsedTime.Milliseconds}ms";
            }));
        }

        /// <summary>
        /// 状态栏刷新，用于委托给语言档管理器反馈操作信息
        /// </summary>
        /// <param name="msg"></param>
        private void UpdateStatusBar(string msg)
        {
            this.tssl_status.Text = msg;
        }

        #region 点击工具栏事件

        /// <summary>
        /// 导入语言文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnImportLangValueFromFile(object? sender, EventArgs e)
        {
            LngFileManager.ImportLangValueFromFile();
            Uc_TextEditor.RefreshAnnotations();
        }

        /// <summary>
        /// 导入语言包
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnImportLangValueFromPak(object? sender, EventArgs e)
        {
            LngFileManager.ImportLangValueFromPak();
            Uc_TextEditor.RefreshAnnotations();
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickSearch(object? sender, EventArgs e)
        {
            tsbtn_Search.Checked = !tsbtn_Search.Checked;
            Uc_Search.Visible = tsbtn_Search.Checked;
            Uc_Search.TextBox.Select();
            Uc_Search.InitSearch(Uc_TextEditor.HighlightText, SimulateNodeMouseClick, LngFileManager);
        }

        /// <summary>
        /// 取消所有标注
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickUnAnnotateAll(object? sender, EventArgs e)
        {
            LngFileManager.AnnotationManager.ClearAllAnnotations();
            Uc_TextEditor.RefreshAnnotations();
        }

        /// <summary>
        /// 取消标注
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickUnAnotateRows(object? sender, EventArgs e)
        {
            Uc_TextEditor.RemoveSelectedAnnotations();
        }

        /// <summary>
        /// 添加标注
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickAnnotateRows(object? sender, EventArgs e)
        {
            Uc_TextEditor.AddSelectedAnnotations();

        }


        /// <summary>
        /// 标注所有
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickAnnotateAll(object? sender, EventArgs e)
        {
            if (LngFileManager.CurrentPackage == null)
            {
                return;
            }
            LngFileManager.AnnotationManager.InitializeAnnotationDict(LngFileManager.CurrentPackage);
            Uc_TextEditor.RefreshAnnotations();
        }

        /// <summary>
        /// 下个未翻译标注
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickNextAnnotation(object? sender, EventArgs e)
        {
            if (LngFileManager.CurrentPackage == null)
            {
                MessageBox.Show("请先导入语言包");
                return;
            }

            MatchAnnotation match = LngFileManager.AnnotationManager.FindNextAnnotation();
            if (match == null)
            {
                return;
            }
            SimulateNodeMouseClick(match.LngFileName);
            Uc_TextEditor.HighlightText(match.MatchText, match.LineIndex, Color.OrangeRed);
        }

        /// <summary>
        /// 上个未翻译标注
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickLastAnnotion(object? sender, EventArgs e)
        {
            if (LngFileManager.CurrentPackage == null)
            {
                MessageBox.Show("请先导入语言包");
                return;
            }

            MatchAnnotation match = LngFileManager.AnnotationManager.FindLastAnnotation();
            if (match == null)
            {
                return;
            }
            SimulateNodeMouseClick(match.LngFileName);
            Uc_TextEditor.HighlightText(match.MatchText, match.LineIndex, Color.OrangeRed);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickSave(object? sender, EventArgs e)
        {
            LngFileManager.Save(UpdateStatusBar);
        }

        /// <summary>
        /// 另存为
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickSaveAs(object? sender, EventArgs e)
        {
            LngFileManager.SaveAs(UpdateStatusBar);
        }

        /// <summary>
        /// 另存为
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickSaveAsIni(object? sender, EventArgs e)
        {
            LngFileManager.SaveAs(UpdateStatusBar, ".ini");
        }

        private void OnClickSaveAsTxt(object? sender, EventArgs e)
        {
            LngFileManager.SaveAs(UpdateStatusBar, ".txt");
        }
        /// <summary>
        /// 点击补充解决方案
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void OnClickTsmiCompleSolution(object? sender, EventArgs e)
        {
            await LngFileManager.CompeleteLngPakFromSolution(PojectLoadUpdateStatusBar, UpdateStatusBar);
            RefreshTreeView();
        }

        /// <summary>
        /// 点击补充项目文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void OnClickTsmiCompleProject(object? sender, EventArgs e)
        {
            await LngFileManager.CompeleteLngPakFromProject(PojectLoadUpdateStatusBar, UpdateStatusBar);
            RefreshTreeView();
        }

        /// <summary>
        /// 点击补充语言包
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickTsmiCompleLangPak(object? sender, EventArgs e)
        {
            LngFileManager.CompeleteLngPakFromFolder(UpdateStatusBar);
            RefreshTreeView();
        }

        /// <summary>
        /// 点击补充语言文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickTsmiCompleLangFile(object? sender, EventArgs e)
        {
            LngFileManager.CompeleteLngPakFromFile(UpdateStatusBar);
            RefreshTreeView();
        }

        /// <summary>
        /// 点击导入解决方案
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void OnClickTsmiInSolution(object? sender, EventArgs e)
        {

            await LngFileManager.GetLngFileFromSolution(PojectLoadUpdateStatusBar, UpdateStatusBar);
            RefreshTreeView();
        }

        /// <summary>
        /// 点击导入项目
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void OnClickTsmiInProject(object? sender, EventArgs e)
        {
            await LngFileManager.GetLngFileFromProject(PojectLoadUpdateStatusBar, UpdateStatusBar);
            RefreshTreeView();
        }

        /// <summary>
        /// 点击导入语言包
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickTsmiInLangPak(object? sender, EventArgs e)
        {
            LngFileManager.GetLngPakFromFolder(UpdateStatusBar);
            RefreshTreeView();
        }

        /// <summary>
        /// 导入语言文件，会清空之前的导入文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void OnClickTsmiInLangFile(object? sender, EventArgs e)
        {
            LngFileManager.GetLngFileFromFile(UpdateStatusBar);
            RefreshTreeView();
        }

        private void OnClickAITranslation(object? sender, EventArgs e)
        {
            ShowAIResponseForm form = new ShowAIResponseForm(LngFileManager);
            form.Show();
        }
        #endregion

        #endregion


        #region protected
        /// <summary>
        /// 注册事件
        /// </summary>
        protected void SetEvents()
        {
            //导入语言文件点击事件
            tsmi_InLangFile.Click += OnClickTsmiInLangFile;
            tsmi_InLangPak.Click += OnClickTsmiInLangPak;
            tsmi_InProject.Click += OnClickTsmiInProject;
            tsmi_InSolution.Click += OnClickTsmiInSolution;
            //补充语言文件点击事件
            tsmi_CompleLangFile.Click += OnClickTsmiCompleLangFile;
            tsmi_CompleLangPak.Click += OnClickTsmiCompleLangPak;
            tsmi_CompleProject.Click += OnClickTsmiCompleProject;
            tsmi_CompleSolution.Click += OnClickTsmiCompleSolution;
            //保存
            tsmi_Save.Click += OnClickSave;
            tsmi_SaveAsLng.Click += OnClickSaveAs;
            tsmi_SaveAsIni.Click += OnClickSaveAsIni;
            tsmi_SaveAsTxt.Click += OnClickSaveAsTxt;
            //标记查找
            tsmi_LastAnnotation.Click += OnClickLastAnnotion;
            tsmi_NextAnnotation.Click += OnClickNextAnnotation;
            tsmi_AnnotateRows.Click += OnClickAnnotateRows;
            tsmi_UnAnotateRows.Click += OnClickUnAnotateRows;
            tsmi_UnAnnotateAll.Click += OnClickUnAnnotateAll;
            tsmi_AnnotateAll.Click += OnClickAnnotateAll;
            tsbtn_Search.Click += OnClickSearch;
            //其它
            tv_Main.NodeMouseClick += OnClickTreeView;
            tsmi_ImportLangValueFromPak.Click += OnImportLangValueFromPak;
            tsmi_ImportLangValueFromFile.Click += OnImportLangValueFromFile;
            //翻译
            tsmi_AITanslation.Click += OnClickAITranslation;
        }



        /// <summary>
        /// 点击树
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void OnClickTreeView(object? sender, TreeNodeMouseClickEventArgs e)
        {
            TreeNode selectedNode = e.Node;
            if (tv_Main.SelectedNode == selectedNode)
            {
                return;
            }
            if (Uc_TextEditor.RichTextBox.Enabled && (MessageBox.Show("是否保存编辑数据?", "保存", MessageBoxButtons.YesNo) == DialogResult.Yes))
            {
                Uc_TextEditor.SaveTextToLngFile();
            }
            tv_Main.SelectedNode = selectedNode;
            tv_Main.Refresh();
            this.Text = $"语言档编辑工具({tv_Main.SelectedNode.Text})";
            string txt = "";
            if (selectedNode.Tag as LanguageFile != null)
            {
                LanguageFile file = (LanguageFile)selectedNode.Tag;
                LngFileManager.SelectedLngFileName = selectedNode.Text;
                LngFileManager.SelectedSectionName = "";
            }
            else if (selectedNode.Parent.Tag as LanguageFile != null)
            {
                LngFileManager.SelectedLngFileName = selectedNode.Parent.Text;
                LngFileManager.SelectedSectionName = selectedNode.Text;
            }
            Uc_TextEditor.InitializeUI();
            Uc_TextEditor.RichTextBox.Text = LngFileManager.GetSelectedText();
            Uc_TextEditor.RefreshAnnotations();
        }


        /// <summary>
        /// 刷新树
        /// </summary>
        protected void RefreshTreeView()
        {
            if (LngFileManager.CurrentPackage == null)
            {
                return;
            }
            tv_Main.Nodes.Clear();
            foreach (LanguageFile file in LngFileManager.CurrentPackage.LanguageFiles)
            {
                string nodeName = Path.GetFileName(file.FilePath);
                TreeNode node = new TreeNode(nodeName) { Tag = file };
                var dict = file.GetIniCache();
                foreach (string sectionName in file.Sections)
                {
                    TreeNode secNode = new TreeNode(sectionName);
                    node.Nodes.Add(secNode);
                }
                tv_Main.Nodes.Add(node);
            }
        }

        #endregion


        #region public
        /// <summary>
        /// 模拟点击树
        /// </summary>
        /// <param name="treeNodeText"></param>
        public void SimulateNodeMouseClick(string treeNodeText)
        {
            TreeNode treeNode = null;
            foreach (TreeNode node in tv_Main.Nodes)
            {
                if (node.Text == treeNodeText)
                {
                    treeNode = node;
                    break;
                }
            }
            if (treeNode == null)
            {
                return;
            }

            // 手动调用事件处理程序
            TreeNodeMouseClickEventArgs args = new TreeNodeMouseClickEventArgs(treeNode, MouseButtons.Left, 1, 0, 0);
            tv_Main.Select();
            OnClickTreeView(treeNode, args);
        }

        #endregion

        #endregion

    }
}
